package com.example.app.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.application.UsersService;
import com.example.infra.po.UsersPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户详情服务实现
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UsersService usersService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 支持用户名、手机号、邮箱登录
        LambdaQueryWrapper<UsersPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UsersPo::getUsername, username)
                .or().eq(UsersPo::getEmail, username);

        UsersPo user = usersService.getOne(wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        return new UserDetailsImpl(user);
    }
}